package com.freecloud.whispered.oss.controller;

import com.freecloud.framework.annotation.CORS;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.framework.request.R;
import com.freecloud.whispered.oss.service.SysOssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @Author: maomao
 * @Date: 2019-07-31 09:37
 */
@Api
@RestController
@RequestMapping("sys/oss")
public class UploadController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysOssService sysOssService;

//    @Autowired
//    private UserOssService userOssService;



    /**
     * 上传文件到OSS远程服务器
     * @param file
     * @param upload
     * @param params
     * @return
     * @throws Exception
     */
    @ApiOperation("上传文件到oss云服务")
    @CORS   //允许跨域请请求
    @PostMapping("/upload")
    public Object upload(@RequestParam(value="file", required=false) MultipartFile file ,
                         @RequestParam(value="upload", required=false) MultipartFile upload,
                         @RequestParam Map<String, Object> params) throws Exception {

        MultipartFile uploadFile = getUploadFile( file, upload);

        Object result = sysOssService.saveUploadFile( uploadFile, params, false);

        if(result instanceof String){
            return result;
        }
        return R.ok().put("data",result);
    }

    /**
     * 上传文件到本地电脑
     */
    @ApiOperation("上传文件到服务器本地")
    @PostMapping("/uploadl")
    @CORS   //允许跨域请请求
    public Object uploadl(@RequestParam(value="file", required=false) MultipartFile file ,
                          @RequestParam(value="upload", required=false) MultipartFile upload,
                          @RequestParam Map<String, Object> params) throws Exception {

        MultipartFile uploadFile = getUploadFile( file, upload);

        Object result = sysOssService.saveUploadFile( uploadFile, params, true);

        if(result instanceof String){
            return result;
        }
        return R.ok().put("data",result);
    }

    /**
     *  获取上传文件对象
     * @param file
     * @param upload
     * @return
     */
    private MultipartFile getUploadFile(MultipartFile file,MultipartFile upload){
        if ((file == null || file.isEmpty()) && (upload == null || upload.isEmpty ())) {
            throw new RRException("上传文件不能为空");
        }

        if(upload != null && !upload.isEmpty () && file != null && !file.isEmpty()){
            throw new RRException("无法同时处理多文件上传！");
        }

        if(upload != null && !upload.isEmpty ())
        {
            return upload;
        }
        return file;
    }
}

